/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.news;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.NewsModuleConstants;
import com.blandware.atleap.common.parsers.html.HTMLPlainTextExtractor;
import com.blandware.atleap.common.util.ConvertUtil;
import com.blandware.atleap.model.news.NewsItem;
import com.blandware.atleap.search.SearchManager;
import com.blandware.atleap.service.exception.BeanAlreadyExistsException;
import com.blandware.atleap.service.news.NewsManager;
import com.blandware.atleap.webapp.action.core.BaseAction;
import com.blandware.atleap.webapp.form.news.NewsItemForm;
import com.blandware.atleap.webapp.util.core.LocaleUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.news.NewsModuleWebConstants;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>Creates new news item
 * </p>
 * <p><a href="CreateNewsItemAction.java.html"><i>View Source</i></a></p>
 * <p/>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @author Andrey Grebnev <a href="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
 * @version $Revision: 1.33 $ $Date: 2008/04/29 17:51:52 $
 * @struts.action path="/news/createItem"
 * name="newsItemForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="news-item-create"
 * @struts.action-forward name="inputForward"
 * path=".news.createItemAnnotation"
 * @struts.action-forward name="listNewsItems"
 * path="/news/listItems.do"
 * redirect="true"
 * @struts.action-forward name="callCreateItem"
 * path=".news.createItem"
 */
public final class CreateNewsItemAction extends BaseAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {

        NewsItemForm newsItemForm = (NewsItemForm) form;
        String localesMode = newsItemForm.getLocalesMode();

		if ( isBackPressed(request) ) {
            // First check, may be session has been invalidated and we need to
            // fill content locales again
            if (request.getSession().getAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY) == null) {
                List contentLocales = LocaleUtil.getInstance(servlet.getServletContext()).getEnabledLocales();
                request.getSession().setAttribute(WebappConstants.CONTENT_LOCALES_COLLECTION_KEY, contentLocales);
            }

            // check 'check all' ckeckbox if needed
            newsItemForm.setAllCheckedFlagForBodyCheckboxes(request, localesMode);

			return mapping.findForward("inputForward");
		}

		if ( isCancelled(request) ) {
			return mapping.findForward("listNewsItems");
		}

		if ( request.getSession().getAttribute(NewsModuleWebConstants.NEWS_ITEM_SUBMITTED_ACTION_KEY) == null ) {
			request.getSession().setAttribute(NewsModuleWebConstants.NEWS_ITEM_SUBMITTED_ACTION_KEY, "create");

			NewsItem newsItem = new NewsItem();
			WebappUtil.copyProperties(newsItem, newsItemForm, request);

			Date publicationDate = newsItem.getPublicationDate();

			// set activity
			Date today = new Date();
			if ( publicationDate.compareTo(today) <= 0 ) {
				newsItem.setActive(Boolean.TRUE);
			} else {
				newsItem.setActive(Boolean.FALSE);
			}

            Map annotationMap = newsItemForm.getAnnotationMap();
            Map bodyMap = newsItemForm.getBodyMap();
            Map annotationCheckedBoxes = newsItemForm.getAnnotationCheckedBoxes();
            Map bodyCheckedBoxes = newsItemForm.getBodyCheckedBoxes();
            for (Iterator i = annotationMap.entrySet().iterator(); i.hasNext();) {
                Map.Entry entry = (Map.Entry) i.next();
                String localeIdentifier = (String) entry.getKey();
                if (annotationCheckedBoxes.get(localeIdentifier) == null) {
                    // if this locale is not checked, remove annotation
                    annotationMap.put(localeIdentifier, "");
                }
            }
            for (Iterator i = bodyMap.entrySet().iterator(); i.hasNext();) {
                Map.Entry entry = (Map.Entry) i.next();
                String localeIdentifier = (String) entry.getKey();
                if (bodyCheckedBoxes.get(localeIdentifier) == null) {
                    // if this locale is not checked, remove body
                    bodyMap.put(localeIdentifier, "");
                }
            }

            WebappUtil.fillFieldValueWithDefaultLocaleValue(newsItemForm.getTitleMap(), newsItem.getTitle(), servlet.getServletContext());
            newsItem.setTitle(newsItemForm.getTitleMap());
            WebappUtil.copyFieldValue(newsItem.getAnnotation(), annotationMap);
            WebappUtil.copyFieldValue(newsItem.getBody(), bodyMap);
			NewsManager newsManager = (NewsManager) getBean(NewsModuleConstants.NEWS_MANAGER_BEAN);

			// get all refs
			HTMLPlainTextExtractor extractor = new HTMLPlainTextExtractor();
			Set refs = new HashSet();
			for ( Iterator i = annotationMap.entrySet().iterator(); i.hasNext(); ) {
				Map.Entry entry = (Map.Entry) i.next();
				String locale = (String) entry.getKey();
				String annotation = (String) entry.getValue();
				String body = (String) bodyMap.get(locale);
                if (annotation != null) {
                    InputStream annotationIS = new ByteArrayInputStream(ConvertUtil.convertToByteArray(annotation));
                    refs.addAll(extractor.extractAllRefs(annotationIS, Constants.DEFAULT_ENCODING));
                }
                if ( !GenericValidator.isBlankOrNull(body) ) {
					InputStream bodyIS = new ByteArrayInputStream(ConvertUtil.convertToByteArray(body));
					refs.addAll(extractor.extractAllRefs(bodyIS, Constants.DEFAULT_ENCODING));
				}
			}

			Map linkedObjects = WebappUtil.mapObjectsToRefs(refs, request.getSession().getServletContext(), request.getContextPath());

			Long newsItemId;
			String uri = null;

			try {
				// we need an ID to create URI of item, so we must first create item, then set URI and update item
				newsItemId = newsManager.createNewsItem(newsItem, linkedObjects);

				uri = NewsModuleWebConstants.NEWS_ITEM_URI_PREFIX + "/item" + newsItemId;
				newsItem.setUri(uri);
				newsManager.updateNewsItem(newsItem, linkedObjects);

				if ( newsItem.getActive().booleanValue() ) {
					// index news item
					SearchManager searchManager = SearchManager.getInstance(request.getSession().getServletContext());
					searchManager.reIndexPage(newsItem, request);
				}

			} catch ( BeanAlreadyExistsException e ) {
				// news item already exists

                // check 'check all' ckeckbox if needed
                newsItemForm.setAllCheckedFlagForBodyCheckboxes(request, localesMode);                

				ActionMessages errors = new ActionMessages();
				errors.add("newsItemAlreadyExists", new ActionMessage("news.errors.alreadyExists", uri));
				saveErrors(request, errors);
				saveToken(request);
				return mapping.getInputForward();
			}
		}
		return mapping.findForward("listNewsItems");
	}
}